<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>{{ album_name }}</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        #jump-input {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 2px 5px;
            border-radius: 4px;
            width: 60px;
            font-family: Arial, sans-serif;
        }

        #jump-input:focus {
            outline: none;
            box-shadow: 0 0 3px rgba(255, 255, 255, 0.5);
        }

        body {
            height: 100vh;
            background: #000;
            overflow: hidden;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }

        .top-nav {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            /*background: rgba(0, 0, 0, 0.6);*/
            /*backdrop-filter: blur(10px);*/
            /*-webkit-backdrop-filter: blur(10px);*/
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            z-index: 1200;
            /*box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);*/
        }

        .top-nav a {
            color: white;
            text-decoration: none;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 15px;
            transition: all 0.3s ease;
        }

        .top-nav .back-btn {
            display: flex;
            align-items: center;
            background: rgba(0, 0, 0, 0.3);
        }

        .top-nav .back-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .top-nav .fullscreen-btn {
            background: rgba(30, 144, 255, 0.7);
        }

        .top-nav .fullscreen-btn:hover {
            background: rgba(30, 144, 255, 0.9);
        }

        .info-box {
            position: fixed;
            top: 60px;
            left: 20px;
            background: rgba(0, 0, 0, 0.6);
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            backdrop-filter: blur(5px);
            z-index: 1000;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        #album-title {
            font-weight: bold;
            {#max-width: 200px;#}
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        @media (max-width: 768px) {
            .info-box {
                top: auto;
                bottom: 20px;
                left: 50%;
                transform: translateX(-50%);
                width: 90%;
                text-align: center;
                padding: 8px 15px;
                flex-wrap: wrap;
                justify-content: center;
            }

            .top-nav {
                padding: 8px 15px;
            }
        }

        .container {
            position: relative;
            height: 100vh;
            width: 100vw;
        }

        .slide {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 0;
        }

        .slide.active {
            opacity: 1;
            z-index: 1;
        }

        .slide img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            user-select: none;
            -webkit-user-select: none;
            -webkit-touch-callout: none;
            transition: all 0.3s ease;
        }

        .slide img.actual-size {
            width: auto;
            height: auto;
            max-width: 100%;
            max-height: 100%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            object-fit: initial;
        }

        .swipe-indicator {
            position: fixed;
            height: 100%;
            width: 50px;
            top: 0;
            background-color: rgba(255, 255, 255, 0.1);
            opacity: 0;
            transition: opacity 0.3s;
            pointer-events: none;
            z-index: 100;
        }

        .swipe-left {
            left: 0;
        }

        .swipe-right {
            right: 0;
        }
    </style>
</head>
<body>
<div class="top-nav">
    <a href="{{ url_for('index') }}" class="back-btn">← 返回相册列表</a>
    <a href="#" onclick="event_full_screen()" class="fullscreen-btn">全屏浏览</a>
</div>

<div class="info-box">
    <span id="album-title">{{ album_name }}</span> •
    <span id="page-info">1/{{ images|length }}</span>
    <input type="number"
           id="jump-input"
           min="1"
           max="{{ images|length }}"
           value="1"
           placeholder="跳转"
           onchange="jumpToPage(this.value)">
    <label style="display: flex; align-items: center; gap: 5px; cursor: pointer;">
        <input type="checkbox" 
               id="fullscreen-mode" 
               checked 
               onchange="toggleImageMode(this.checked)"
               style="cursor: pointer;">
        <span>全屏显示</span>
    </label>
</div>

<!-- 滑动指示器 -->
<div class="swipe-indicator swipe-left" id="swipe-left"></div>
<div class="swipe-indicator swipe-right" id="swipe-right"></div>

<div class="container">
    {% for image in images %}
        <div class="slide{% if loop.first %} active{% endif %}" data-index="{{ loop.index }}">
            <img src="{{ url_for('custom_static',albumname=album_name, filename=image.filename) }}" alt="{{ image.filename }}">
        </div>
    {% endfor %}
</div>

<script>
    let currentSlide = 1;
    const slides = document.querySelectorAll('.slide');
    const totalSlides = slides.length;
    const albumMd5 = "{{album_md5}}"; // 从Python后端获取相册名称的MD5值

    // 保存索引到cookie的函数
    function saveIndexToCookie(index) {
        const cookieName = `slideIndex_${albumMd5}`;
        const expireDays = 30; // cookie保存30天
        const date = new Date();
        date.setTime(date.getTime() + (expireDays * 24 * 60 * 60 * 1000));
        const expires = `expires=${date.toUTCString()}`;
        document.cookie = `${cookieName}=${index};${expires};path=/`;
    }

    // 从cookie读取索引的函数
    function getIndexFromCookie() {
        const cookieName = `slideIndex_${albumMd5}`;
        const name = cookieName + "=";
        const decodedCookie = decodeURIComponent(document.cookie);
        const cookieArray = decodedCookie.split(';');

        for (let i = 0; i < cookieArray.length; i++) {
            let cookie = cookieArray[i].trim();
            if (cookie.indexOf(name) === 0) {
                return parseInt(cookie.substring(name.length, cookie.length)) || 1;
            }
        }
        return 1; // 默认返回第一张
    }

    function updatePageInfo() {
        document.getElementById('page-info').textContent = `${currentSlide}/${totalSlides}`;
    }

    // 新增跳转函数
    function jumpToPage(value) {
        let page = parseInt(value);
        if (isNaN(page)) return;
        page = Math.max(1, Math.min(page, totalSlides));
        showSlide(page);
        document.getElementById('jump-input').value = page;  // 修正非法值
    }

    // 新增图片显示模式切换函数
    function toggleImageMode(isFullscreen) {
        const images = document.querySelectorAll('.slide img');
        images.forEach(img => {
            if (isFullscreen) {
                img.classList.remove('actual-size');
            } else {
                img.classList.add('actual-size');
            }
        });
        
        // 保存用户偏好到localStorage
        localStorage.setItem('imageDisplayMode', isFullscreen ? 'fullscreen' : 'actual-size');
    }

    function showSlide(index) {
        // 限制切换范围
        if (index < 1) index = 1;
        if (index > totalSlides) index = totalSlides;

        slides.forEach(slide => slide.classList.remove('active'));
        currentSlide = index;
        slides[currentSlide - 1].classList.add('active');
        updatePageInfo();
        document.getElementById('jump-input').value = currentSlide;

        // 保存当前索引到cookie
        saveIndexToCookie(currentSlide);

        console.log(`切换到幻灯片 ${currentSlide}`);

        // 到达最后一张自动退出全屏
        if (currentSlide === totalSlides && document.fullscreenElement) {
            document.exitFullscreen();
        }
    }

    // 键盘控制
    document.addEventListener('keydown', (e) => {
        switch (e.key) {
            case 'ArrowLeft':
                showSlide(currentSlide - 1);
                break;
            case 'ArrowRight':
                showSlide(currentSlide + 1);
                break;
        }
    });

    // 优化的滚轮控制（防抖）
    let wheelTimeout;
    document.addEventListener('wheel', (e) => {
        e.preventDefault();
        
        // 清除之前的超时
        clearTimeout(wheelTimeout);
        
        // 设置新的超时，防止过于频繁的切换
        wheelTimeout = setTimeout(() => {
            e.deltaY > 0 ? showSlide(currentSlide + 1) : showSlide(currentSlide - 1);
        }, 50);
    }, {passive: false});

    // 全屏切换控制
    function event_full_screen() {
        // 忽略滑动操作产生的点击事件
        if (document.fullscreenElement) {
            document.exitFullscreen();
        } else {
            document.documentElement.requestFullscreen().catch(err => {
                console.log('全屏请求失败:', err);
            });
        }
    }

    // 页面加载时，读取cookie并显示对应的图片
    document.addEventListener('DOMContentLoaded', function () {
        console.log(`初始化幻灯片，totalSlides: ${totalSlides}`);
        
        // 确保页面信息显示正确
        updatePageInfo();
        
        // 从localStorage读取用户的显示偏好
        const savedDisplayMode = localStorage.getItem('imageDisplayMode');
        const checkbox = document.getElementById('fullscreen-mode');
        
        if (savedDisplayMode === 'actual-size') {
            checkbox.checked = false;
            toggleImageMode(false);
        } else {
            checkbox.checked = true;
            toggleImageMode(true);
        }
        
        // 从cookie获取上次浏览的索引
        let savedIndex = getIndexFromCookie();
        
        // 确保索引有效
        if (savedIndex < 1 || savedIndex > totalSlides) {
            savedIndex = 1;
        }
        
        // 如果保存的索引不是1，则切换到该索引
        if (savedIndex !== 1) {
            showSlide(savedIndex);
        }
        
        console.log(`幻灯片初始化完成，当前: ${currentSlide}`);
    });

    // 触摸滑动控制
    let touchStartX = 0;
    let touchEndX = 0;

    document.addEventListener('touchstart', (e) => {
        touchStartX = e.changedTouches[0].screenX;

        // 阻止默认行为，避免触发其他元素的点击
        if (e.target.tagName === 'IMG') {
            e.preventDefault();
        }
    }, {passive: false});

    document.addEventListener('touchmove', (e) => {
        const currentX = e.changedTouches[0].screenX;
        const diff = currentX - touchStartX;

        // 显示滑动指示器
        if (diff > 30) {
            document.getElementById('swipe-right').style.opacity = '0.5';
            document.getElementById('swipe-left').style.opacity = '0';
        } else if (diff < -30) {
            document.getElementById('swipe-left').style.opacity = '0.5';
            document.getElementById('swipe-right').style.opacity = '0';
        }
    });

    document.addEventListener('touchend', (e) => {
        touchEndX = e.changedTouches[0].screenX;

        // 隐藏滑动指示器
        document.getElementById('swipe-left').style.opacity = '0';
        document.getElementById('swipe-right').style.opacity = '0';

        handleSwipe();
    });

    function handleSwipe() {
        const swipeThreshold = 50; // 滑动阈值，防止误触
        window.swiping = true; // 标记正在进行滑动操作

        if (touchEndX < touchStartX - swipeThreshold) {
            // 向左滑动，显示下一张
            showSlide(currentSlide + 1);
        }
        if (touchEndX > touchStartX + swipeThreshold) {
            // 向右滑动，显示上一张
            showSlide(currentSlide - 1);
        }

        // 滑动操作结束后重置标记
        setTimeout(() => {
            window.swiping = false;
        }, 300);
    }
</script>
</body>
</html>